<template>
    <div class="ticket-create-wrap">
        <!-- 首部选择栏 -->
        <div class="type">
            <div class="head-tip margin-top-8">
                <span>新建{{ticketType[type-1]}}工单</span>
            </div>

            <div class="type-list margin-top-30 margin-bottom-20">
                <RadioGroup size="large" type="button" v-model="type">
                    <Radio
                        :disabled="isEdit && type !== index + 1"
                        :key="index"
                        :label="index + 1"
                        v-for="(item, index) in ticketType"
                    >{{item}}工单</Radio>
                </RadioGroup>

                <p class="margin-bottom-20 margin-top-10">{{tip}}</p>
            </div>
        </div>

        <!-- 表单内容 -->
        <div class="form">
            <div class="head-tip margin-top-8">
                <span>工单内容</span>
            </div>

            <div class="type-list margin-top-30">
                <Form :label-width="120" :model="form" :rules="rules" :show-message="false" label-position="right" ref="createAppointment">
                    <!-- 下单人信息 -->
                    <Row :gutter="16" class="margin-top-20">
                        <i-col span="12">
                            <FormItem label="下单人：" prop="subscribe.name">
                                <i-input placeholder="必填" v-model="form.subscribe.name"></i-input>
                            </FormItem>
                        </i-col>
                        <i-col span="12">
                            <FormItem label="下单人电话：" prop="subscribe.phone">
                                <Input placeholder="必填" v-model="form.subscribe.phone"></Input>
                            </FormItem>
                        </i-col>
                    </Row>

                    <!-- 现场联系人信息 -->
                    <Row :gutter="16">
                        <i-col span="12">
                            <FormItem label="现场联系人：" prop="contact_person.name">
                                <i-input placeholder="必填" v-model="form.contact_person.name"></i-input>
                            </FormItem>
                        </i-col>
                        <i-col span="12">
                            <FormItem label="现场联系电话：" prop="contact_person.phone">
                                <Input placeholder="必填" v-model="form.contact_person.phone"></Input>
                            </FormItem>
                        </i-col>
                    </Row>

                    <!-- 公寓地址 -->
                    <FormItem class="apartment" label="公寓地址：" prop="home_id">
                        <Select
                            :loading="loadingHomes"
                            :remote-method="searchHomes"
                            @on-change="getRoom"
                            clearable
                            filterable
                            placeholder="请输入公寓地址(只展示10条数据,可输入关键词远程搜索)"
                            ref="homes"
                            remote
                            v-if="!fixedHome"
                        >
                            <Option
                                :key="index"
                                :value="option.id"
                                v-for="(option, index) in homes"
                            >{{concatLocation(option) + '(' + option.home_name + ')'}}</Option>
                        </Select>
                        <i-input :readonly="fixedHome" :value="homes.length ? concatLocation(homes[0]) : ''" v-else></i-input>
                    </FormItem>

                    <!-- 房间号 -->
                    <div v-if="isInstallOrReinstall">
                        <FormItem label="房间号：">
                            <Select
                                :disabled="!form.home_id"
                                @on-change="handleSelecAll"
                                multiple
                                filterable
                                placeholder="请选择房间 (可多选)"
                                v-model="selectedRooms"
                            >
                                <Option value="all">{{selectAll ? '取消全选' : '全选'}}</Option>
                                <Option :key="index" :value="item.id" v-for="(item, index) in rooms">{{item.room_name}}</Option>
                            </Select>
                        </FormItem>
                        
                        <!-- 展示选中多少个房间 -->
                        <FormItem v-show="selectedRooms.length">
                            共选中{{selectedRooms.length}}个房间
                        </FormItem>

                        <FormItem label="设备类型：" prop="service_target">
                            <Select
                                :disabled="isEdit"
                                @on-change="handleDeviceTypeChange"
                                placeholder="请选择设备类型"
                                v-model="form.service_target"
                            >
                                <Option :key="index" :value="device.id" v-for="(device,index) in deviceType">{{device.name}}</Option>
                            </Select>
                        </FormItem>

                        <transition name="ease">
                            <FormItem :label="`${type === 4 ? '重装' : '下单'}设备：`" class="ivu-form-item-required" :class="type === 4 ? 'hideMandatory' : ''" v-if="shouldShowDeviceModel">
                                <div style="margin-bottom: -10px">
                                    <Row
                                        :gutter="10"
                                        :key="key"
                                        class="margin-bottom-10"
                                        type="flex"
                                        v-for="(device, key) in form.product_device_list"
                                    >
                                        <i-col span="10">
                                            <FormItem :prop="'product_device_list.' + key + '.device_product_id'" :rules="{required: type !== 4}">
                                                <Select
                                                    @on-change="(val) => handleModelChange(val, key)"
                                                    not-found-text="无设备库存"
                                                    v-model="device.device_product_id"
                                                >
                                                    <Option
                                                        :disabled="selectedProducts.includes(model.id)"
                                                        :key="model.id"
                                                        :value="model.id"
                                                        v-for="model in deviceModel"
                                                    >{{model.name}}</Option>
                                                </Select>
                                            </FormItem>
                                        </i-col>
                                        <i-col span="10" v-if="deviceModel && deviceModel.length">
                                            <FormItem :prop="'product_device_list.' + key + '.estimate_quantity'" :rules="{required: type !== 4}">
                                                <Tooltip
                                                    :content="'最大数量:' + (device.maxCount !== undefined ? device.maxCount : '总数小于房间数量')"
                                                    class="full-tool"
                                                >
                                                    <InputNumber
                                                        :max="device.maxCount || 1000"
                                                        :min="1"
                                                        class="width-100p"
                                                        v-model="device.estimate_quantity"
                                                    ></InputNumber>
                                                </Tooltip>
                                            </FormItem>
                                        </i-col>
                                        <i-col span="4" v-if="deviceModel && deviceModel.length">
                                            <i-button @click="handleAddDevice" icon="plus" v-if="key === 0"></i-button>
                                            <i-button @click="handleDeleteDevice(key)" icon="minus" v-if="key !== 0"></i-button>
                                        </i-col>
                                    </Row>
                                </div>
                            </FormItem>
                        </transition>

                        <FormItem label="期望上门时间：">
                            <Row :gutter="10" type="flex">
                                <i-col span="12">
                                    <FormItem>
                                        <DatePicker
                                            :options="options"
                                            format="yyyy-MM-dd"
                                            placeholder="请选择时间"
                                            style="width: 100%"
                                            type="date"
                                            v-model="expected_time"
                                        ></DatePicker>
                                    </FormItem>
                                </i-col>
                                <i-col span="12">
                                    <FormItem prop="subscribe.expected_period">
                                        <Select v-model="form.subscribe.expected_period">
                                            <Option :value="1">全天</Option>
                                            <Option :disabled="isNotTodayMoring" :value="2">上午</Option>
                                            <Option :value="3">下午</Option>
                                        </Select>
                                    </FormItem>
                                </i-col>

                                <p class="red" v-show="isNotLegalInstallTime">截止到{{cutoffDay}}的工单已派单，如需追加工单，请拨打客服热线：4000-101-110</p>
                            </Row>
                        </FormItem>

                        <FormItem label="备注：" prop="subscribe.note">
                            <i-input :autosize="{minRows: 3, maxRows: 4}" placeholder="请输入备注" type="textarea" v-model="form.subscribe.note"></i-input>
                        </FormItem>
                    </div>

                    <div class="repair-list" v-else>
                        <div :key="index" class="repair-item" v-for="(item, index) in faultModel">
                            <!-- 房间号 -->
                            <FormItem label="房间号：">
                                <Row :gutter="10" type="flex">
                                    <i-col span="20">
                                        <Select @on-change="(()=>{item.device_id = ''})" placeholder="请选择房间号(必填)" v-model="item.room_id">
                                            <Option :key="room.id" :value="room.id" v-for="room in rooms">{{room.room_name}}</Option>
                                        </Select>
                                    </i-col>
                                    <i-col span="4">&nbsp;
                                        <i-button @click="handleNewDelete(index)">删除</i-button>
                                    </i-col>
                                </Row>
                            </FormItem>

                            <!-- 故障设备 -->
                            <FormItem :label="`${type === 2 ? '故障' : '拆卸'}设备：`">
                                <Select :disabled="!!item.sn" placeholder="请选择故障设备(必填)" v-model="item.device_id">
                                    <Option
                                        :disabled="selectedDevices.includes(device.id) && device.id !== -1"
                                        :key="device.id"
                                        :value="device.id"
                                        v-for="device in devices[item.room_id]"
                                    >
                                        {{device.description}}
                                        [{{(isEdit && !!item.sn) ? item.product_type : deviceTypes[device.device_type]}}]
                                    </Option>
                                </Select>
                            </FormItem>

                            <FormItem :label="`${type === 2 ? '故障' : '拆卸'}说明：`">
                                <Input :placeholder="type === 2 ? '请填写故障说明(必填)' : '请填写拆卸说明'" v-model="item.description"></Input>
                            </FormItem>

                            <FormItem label="故障时间：" v-if="type === 2">
                                <DatePicker
                                    :options="faultOptions"
                                    format="yyyy-MM-dd HH:ss"
                                    placeholder="请选择时间"
                                    style="width: 100%"
                                    type="datetime"
                                    v-model="item.fault_time"
                                ></DatePicker>
                            </FormItem>
                        </div>
                    </div>
                </Form>

                <div class="btn-wrap">
                    <i-button
                        @click="deviceAdd"
                        style="margin-right: 10px"
                        type="primary"
                        v-if="!isInstallOrReinstall"
                    >添加{{ticketType[type - 1]}}设备</i-button>
                    <Button :loading="loading" @click="submitData" type="primary">{{isEdit ? '提交修改' : '提交'}}</Button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import debounce from 'lodash/debounce'
import { http, api } from '@/libs/http'
import dayjs from 'dayjs'
import util from '@/libs/util'
import validate from '@/libs/validate.js'
import dataCenter from '@/libs/dataCenter'
import EventBus from '@/libs/event-bus'
export default {
  props: {
    home: [Object],
    ticket: Object,
    fixedHome: Boolean // 是否为外部传入的房源
  },

  mounted () {
    this.resetForm()
    if (!this.fixedHome) {
      this.getHomeList() // 初始化获取房间列表
    }
    this.fetchClientInfo()
    const defaultExceptedTime = dayjs().hour() < 18 ? dayjs().add(1, 'days').toDate() : dayjs().add(2, 'days').toDate()
    this.defaultExceptedTime = defaultExceptedTime
    this.expected_time = defaultExceptedTime
  },

  data () {
    return {
      defaultExceptedTime: '',
      loadingHomes: false,
      isPayFirst: false, // 商户是否现款后货
      isEdit: false, // false => 新建 true => 编辑
      type: 1,
      ticketType: ['新装', '维修', '拆卸', '重装'],
      devicesModel: {
        device_product_id: '',
        estimate_quantity: 0
      },
      form: {
        // 表单数据
        subscribe: {
          name: '',
          phone: '',
          note: '',
          expected_time: '',
          expected_period: 1
        },
        contact_person: {
          name: '',
          phone: ''
        },
        product_device_list: [
          {
            device_product_id: '',
            estimate_quantity: 0
          }
        ],
        home_id: '', // 房源id
        faults: [],
        service_target: -1 // 设备类型
      },
      rules: {
        home_id: { required: true },
        service_target: [{ required: true, message: '请填写手机号码' }, { validator: validate.validIntege1 }],
        faults: { required: true, type: 'array' },
        'contact_person.name': { required: true },
        'contact_person.phone': [{ required: true, message: '请填写手机号码' }, { validator: validate.validPhone }],
        'subscribe.name': { required: true },
        'subscribe.phone': [{ required: true, message: '请填写手机号码' }, { validator: validate.validPhone }]
      },
      clientId: '', // 商户id
      clients: [], // 商户列表
      homes: [], // 房源列表
      deviceModel: [], // 当前设备类型下的设备型号
      faultModel: [], // 维修或者拆卸工单数据模型
      rooms: [],
      editRooms: '', // 编辑时候的房间id列表
      selectedRooms: [],
      ticketId: '', // 工单id
      options: {
        disabledDate (date) {
          return date && date.valueOf() < Date.now() - 86400000
        }
      },
      faultOptions: {
        disabledDate (date) {
          return date && date.valueOf() > Date.now()
        }
      },
      loadingClients: false,
      selectAll: false,
      loading: false,
      devices: {}, // 存放房源下所有房间的相关设备
      deviceType: [
        { id: 1, name: '仅装网关' },
        { id: 2, name: '有网关门锁' },
        { id: 3, name: '电表' },
        { id: 4, name: '无网关门锁' },
        { id: 6, name: '冷水表' },
        { id: 7, name: '热水表' }
      ],
      deviceTypes: {
        1: '网关',
        2: '门锁',
        3: '电表',
        4: '采集器',
        5: '水表网关',
        6: '冷水表',
        7: '热水表'
      },
      expected_time: '' // 期待上门时间
    }
  },

  computed: {
    /**
         * 商户类型为先款后货，且下单商品为【电表、门锁和无网关门锁】，则必须填写下单设备类型 和 设备数量
         * 下单商品为【冷水表或热水表】，则不显示填写下单设备类型 和 设备数量
         * 新建重装工单都要显示下单设备
         */
    shouldShowDeviceModel () {
      return (this.form.service_target > 0 && [1, 2, 3, 4].includes(this.form.service_target) && this.isPayFirst) || this.type === 4
    },

    selectedProducts () {
      return this.form.product_device_list.map(item => item.device_product_id)
    },

    tip () {
      if (this.type === 1) {
        return '如需安装新设备，请下新装工单'
      } else if (this.type === 2) {
        return '如设备出现故障，请下维修工单'
      } else if (this.type === 3) {
        return '如需将设备解绑，请下拆卸工单'
      } else {
        return '如需将已安装设备重绑或已拆卸设备重绑，请下重装工单'
      }
    },

    isNotTodayMoring () {
      const todayStartTime = dayjs().startOf('day').valueOf()

      const leftTime = this.expected_time.valueOf() - todayStartTime
      if (leftTime >= 0 && leftTime < 86400000) {
        const now_hour = dayjs().hour()
        if (now_hour >= 12 && now_hour < 24) {
          return true
        }
        return false
      }
      return false
    },

    isInstallOrReinstall () {
      if (this.type === 1 || this.type === 4) {
        return true
      } else {
        return false
      }
    },

    selectedDevices () {
      return this.faultModel.map(item => item.device_id)
    },
    /**
         * 派单截止日期 = 默认期望时间 - 1天
         */
    cutoffDay () {
      const { defaultExceptedTime } = this
      if (!defaultExceptedTime) return ''
      return dayjs(defaultExceptedTime).subtract(1, 'd').format('YYYY-MM-DD')
    },
    isNotLegalInstallTime () {
      const { type, defaultExceptedTime, expected_time } = this
      if (![1, 4].includes(type)) return false
      if (!defaultExceptedTime || !expected_time) return false
      const defaultTimestamp = dayjs(defaultExceptedTime).startOf('day').valueOf()
      const selectedTimestamp = dayjs(expected_time).startOf('day').valueOf()
      return selectedTimestamp < defaultTimestamp
    }
  },

  watch: {
    type (newVal) {
      this.resetForm(true)
      !this.fixedHome && this.getHomeList()
    },

    '$store.state.user.userName' () {
      this.setDefaultForms()
    },

    '$route.query' (value) {
      // 陆游发生改变
      const { service_type } = value

      if (service_type) {
        this.type = Number(service_type)
      }
    }
  },

  methods: {
    concatLocation: util.concatAddress,

    /**
         * 获取商户信息详情
         */
    async fetchClientInfo () {
      const info = await http.fetch(this, api.client_finance_info)
      this.isPayFirst = info && info.payment_type === 3
    },

    async getHomeList () {
      try {
        const { homes } = await http.fetch(this, api.home_list, null, { kewword: '' })
        this.homes = homes
      } catch (err) {
        console.log(err)
      }
    },

    searchHomes: debounce(function (query) {
      if (query) {
        let params = {
          keyword: query
        }
        this.loadingHomes = true
        http.request(this, api.home_list, null, params, res => {
          if (res) {
            this.homes = res.homes
          }
          this.loadingHomes = false
        })
      }
    }, 300),

    /**
         * 初始化房源数据
         */
    resetHomeData () {
      this.form.home_id = '' // 初始化房源id
      this.homes = [] // 初始化房源列表
    },

    /**
         * 初始化房间数据
         */
    resetRoomData () {
      this.rooms = [] // 初始化房间数据
      this.selectedRooms = [] // 已经选择的房源id
      this.devices = {} // 房源下房间的设备
    },

    /**
         * 通过选择的房间id获取相关房间
         */
    getRoom (home_id, pos = false) {
      this.form.home_id = home_id
      if (!pos && !this.form.home_id) {
        return
      }
      this.resetRoomData()
      http.request(
        this,
        api.room_list,
        [home_id],
        { with_device: 1 },
        (res, err) => {
          if (!res || err) {
            if (err && err.status === 403) this.$Message.error({ content: '该房源不在你的区域范围内', duration: 3 })
          } else {
            const deviceList = {}
            res.forEach(room => {
              const { id, devices } = room
              deviceList[id] = devices
            })
            this.devices = deviceList
            this.rooms = res
          }
        },
        true
      )
    },

    /**
         * 型号改变时候检查库存
         * @param {{}} index form.product_device_list的item的index
         */
    async handleModelChange (type, index, notReset) {
      if (type === undefined || index === undefined) return
      const select = this.deviceModel.find(model => model.id === type)
      this.$set(this.form.product_device_list[index], 'maxCount', select.client_order_statistics[0].real_quantity)
      !notReset && this.$set(this.form.product_device_list[index], 'estimate_quantity', 1)
    },

    handleSelecAll (value) {
      if (value.includes('all')) {
        this.selectAll = !this.selectAll
        if (this.selectAll) {
          const result = this.rooms.map((room, index) => {
            return room.id
          })
          this.selectedRooms = [...result]
        } else {
          this.selectedRooms = []
        }
      }
    },

    /**
         * 选择了详细的设备类型
         */
    handleDeviceTypeChange (type) {
      if (type) {
        this.getDeviceModel(type)
        this.handleResetDevice()
      }
    },

    async getDeviceModel (deviceType) {
      try {
        this.deviceModel = await dataCenter.getDeviceModel(this, deviceType, this.clientId, this.type === 4)
        util.log('重装设备记录-=-=-=-=', this.deviceModel)
        const deviceMap = {}
        this.deviceModel.forEach(item => {
          deviceMap[item.id] = item.name
        })
        this.deviceMap = deviceMap
      } catch (err) {
        console.error(err)
      }
    },

    /** 添加下单设备 */
    handleAddDevice () {
      this.form.product_device_list.push({ ...this.devicesModel })
    },

    handleDeleteDevice (index) {
      this.form.product_device_list.splice(index, 1)
    },

    handleResetDevice () {
      this.form.product_device_list = [{ ...this.devicesModel }]
    },

    handleNewDelete (index) {
      if (this.faultModel.length === 1) {
        this.$Message.error('至少填写一个故障设备')
        return
      }
      this.faultModel.splice(index, 1)
    },

    deviceAdd () {
      this.faultModel.push({
        room_id: -1,
        device_id: -1,
        description: '',
        fault_time: new Date()
      })
    },

    formatTime (value, pos = true) {
      return pos ? dayjs(value).format('YYYY-MM-DD') : dayjs(value).format('YYYY-MM-DD hh:mm:ss')
    },

    /**
         * 重制表格数据
         */
    resetForm () {
      this.$refs.homes && this.$refs.homes.setQuery(null)
      this.$refs.createAppointment.resetFields()
      if (!this.isInstallOrReinstall) {
        this.faultModel = [
          {
            room_id: -1,
            device_id: -1,
            description: '',
            fault_time: new Date()
          }
        ]
      }
      this.form.faults = []
      this.clients = []
      this.clientId = ''
      if (!this.fixedHome) {
        // this.homes = [] // 房源列表
        this.homes = []

        // console.log('change', this.flag, this.homes);
        this.rooms = []
      } else {
        this.homes = [
          {
            ...this.ticket.home_info,
            id: this.ticket.home_id
          }
        ]
        this.form.home_id = this.ticket.home_id
        this.getRoom(this.ticket.home_id)
      }
      this.deviceModel = [] // 当前设备类型下的设备型号
      this.devices = {}
      this.selectedRooms = []
      this.selectAll = false
      this.setDefaultForms()
    },

    // 设备默认联系人
    setDefaultForms () {
      this.form.subscribe.name = this.$store.state.user.userName
      this.form.subscribe.phone = this.$store.state.user.telephone
    },

    /**
         * 构造房间数据
         */
    constructRooms () {
      let { length } = this.selectedRooms

      if (!length) {
        return false
      }

      this.form.faults = this.selectedRooms.map(room_id => {
        return { room_id }
      })

      return true
    },

    /**
         * 构造故障/拆卸 设备
         */
    constructFaultDevice (isFault) {
      const { length } = this.faultModel
      let pos = true

      for (let i = 0; i < length; i++) {
        const { room_id, device_id, description } = this.faultModel[i]

        if (room_id === -1 || device_id === -1 || (isFault && description === '')) {
          pos = false
          break
        }
      }

      if (pos) {
        this.form.faults = this.faultModel.map(value => {
          const { fault_time } = value

          return { ...value, fault_time: new Date(fault_time).valueOf() }
        })
      }

      return pos
    },

    /**
        *  判断当前房间的设备是否达到上限, 限制参考如下链接
        *  https://ydwiki.dding.net/pages/viewpage.action?pageId=11634670
        */
    inspectRoomDeviceLimit () {
      const rules = [ // 设备过滤黑名单
        {
          position: [2, 4], // 门锁每个房间最多装一把
          max: 1
        },
        {
          position: [6, 7], // 水表每个房间最多装两个
          max: 2
        },
        {
          position: [3], // 电表除A1Z和A4p可以装4个，其他最多装一个
          max: [1, 4]
        }
      ]

      return new Promise((resolve, reject) => {
        const { service_target } = this.form // 设备类型

        const selectedRooms = this.rooms.filter(room => this.selectedRooms.includes(room.id)) // 获取选中的房间信息详情
        const rule = rules.find(rule => rule.position.includes(service_target))

        if (!rule) { // 如果不在黑名单内不做判断
          resolve(false)
          return
        }

        const { max, position } = rule
        const errRooms = selectedRooms.reduce((prev, room) => { // 获取超标的房间
          const devices = room.devices.filter(device => position.includes(device.device_type)) // 只判断选中的设备类型

          if (Array.isArray(max)) {
            if (devices.length) {
              let { sn } = devices[0] // 如果房间存在电表取第一个，如果第一个是A4类型那么其他的也肯定是A4类型

              const a4_type = ['05', '06', '11', '12'] // A4类型

              // console.log(sn, a4_type.includes(sn.substring(6, 8)), devices.length);
              if (devices.length >= (a4_type.includes(sn.substring(6, 8)) ? max[1] : max[0])) {
                prev.push(room)
              }
            }
          } else { // 非电表
            if (devices.length >= max) { // 判断是否大于最大数
              prev.push(room)
            }
          }

          return prev
        }, [])

        if (errRooms.length) { // 过滤掉错误房间的
          this.$Modal.info({
            title: '提示',
            content: `房间“${errRooms.map(r => r.room_name).join(',')}”已达可安装设备上限，将去除这些房间`,
            onOk: () => {
              const errorRoomIds = errRooms.map(r => r.id)
              this.selectedRooms = this.selectedRooms.filter(roomId => !errorRoomIds.includes(roomId))
              resolve(false)
            }
          })
        } else {
          resolve(false)
        }

        // console.log('errRooms', errRooms); // 有问题的房间
      })
    },

    /**
         * 提交表单
         */
    submitData () {
      this.loading = true
      this.$refs.createAppointment.validate(async valid => {
        if (!valid) {
          this.$Message.error('请完整填写表单数据')
          this.loading = false
          return
        }

        if (this.isInstallOrReinstall) {
          // if (this.type === 1) { // 判断选择的房间安装的设备类型是否已达到房间所能安装的该类型的上限
          //     await this.inspectRoomDeviceLimit();
          // }

          // 安装或者重装工单的情况下
          if (!this.constructRooms()) {
            this.$Message.error('请至少选择一个房间')
            this.loading = false
            return
          }

          if (!this.isPayFirst && this.type === 1) {
            this.form.product_device_list = [{}]
          }

          this.form.product_device_list = this.form.product_device_list.filter(item => item.estimate_quantity)

          this.form.subscribe.expected_time = new Date(this.expected_time).valueOf()
        } else {
          // 维修或者拆卸工单的情况下
          const { name, phone } = this.form.subscribe

          if (!this.constructFaultDevice(this.type === 2)) {
            this.$Message.error(`请完整填写${this.type === 2 ? '故障' : '拆卸'}设备表单信息`)
            this.loading = false
            return
          }

          this.form.product_device_list = [{}] // 防止接口报错

          this.form.subscribe = {
            name,
            phone
          }
        }

        http.request(this, api.ticket_add, [this.type], this.form, (res, err) => {
          this.loading = false
          if (err || !res) return
          if (this.fixedHome) this.$emit('on-close')
          EventBus.$emit('REFRESH_TICKET_LIST')
          this.$Message.success('添加成功')
          this.resetForm()
          // this.$store.dispatch('addTicketTab', {
          //     type: 'detail',
          //     ticket: res
          // });
          // this.$router.push({
          //     path: `/ticket/detail/${res.id}`
          // });
        })
      })
    }
  }
}
</script>

<style lang="less">
.red {
    color: #f00;
}

.type {
    &-list {
        padding-left: 70px;
    }
}

.head-tip {
    padding-bottom: 10px;
    border-bottom: 1px solid rgba(0, 0, 0, 0.2);

    span {
        font-size: 18px;
    }
}

.form {
    .type-list {
        width: 650px;
    }
}

.btn-wrap {
    display: flex;
    justify-content: flex-end;
}

.repair {
    &-item {
        border-top: 1px solid rgba(0, 0, 0, 0.2);
        padding-top: 24px;
    }
}

// modal中的样式
.ivu-modal-body .ticket-create-wrap {
    padding-bottom: 20px;
    .type-list {
        padding-left: 10px;
    }
    .repair-item {
        margin-top: 10px;
        padding-top: 8px;
    }
    .ivu-form-item {
        margin: 6px 0;
    }
    .margin-top-20 {
        margin-top: 10px;
    }
    .margin-bottom-20 {
        margin-bottom: 10px;
    }
    .margin-top-30 {
        margin-top: 10px;
    }
}

.hideMandatory .ivu-form-item-label:before{
    content: '';
    display: inline-block;
    margin-right: 4px;
    line-height: 1;
    font-family: SimSun;
    font-size: 12px;
    color: #fff;
}
</style>
